package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class    UserController {
    @Autowired
    UserService userService;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        //ValidateCodeUtils
        if(StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //SMSUtils.sendMessage("antman","SMS_136010026",phone,code);
            System.out.println(code);
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }else {
            return R.error("验证码发送失败");
        }
    }
    @PostMapping("/login")
    public R loginPhone(@RequestBody Map map, HttpSession session){
        //通过传来的对象拿到手机号 和验证码
        String phone =  map.get("phone").toString();
        String code =  map.get("code").toString();
        //拿到session中传的真实验证码
        Object sessionCode = session.getAttribute(phone);
        //如果session中的验证码不为null并且session中的验证码和传来的验证码一致 说明登陆成功
        if(sessionCode!=null&&sessionCode.equals(code)){
            //通过传来的phone跟数据库进行匹配 得到一个user对象
            QueryWrapper<User> qw=new QueryWrapper<>();
            qw.lambda().eq(User::getPhone,phone);
            User user = userService.getOne(qw);
            //如果查不到说明是新用户 保存到数据库
            if(user==null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success("登陆成功");
        }
        return R.error("登陆失败");
    }
    @PostMapping("/loginout")
    public R out(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
}
